package cn.shop.lib_common;

import android.content.Context;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by Administrator on 2016/3/31.
 */
public class ComViewHolder {

    private final View view;
    SparseArray<View> views = new SparseArray<>();

    /**
     * 返回
     *
     * @param context
     * @param view
     * @param LayoutRes
     * @return
     */
    public static ComViewHolder newInstance(Context context, View view, int LayoutRes) {
        if (view == null) {
            view = View.inflate(context, LayoutRes, null);
            return new ComViewHolder(view);
        } else {
            return (ComViewHolder) view.getTag();
        }
    }

    private ComViewHolder(View view) {
        this.view = view;
        view.setTag(this);
    }

    /**
     * 返回携带有BaseViewHolder的View
     *
     * @return
     */
    public View getView() {
        return view;
    }

    /**
     * 提供获取控件的方法
     *
     * @param id
     * @param <T>
     * @return
     */
    public <T extends View> T getView(int id) {
        if (views.get(id) == null) {
            views.put(id, view.findViewById(id));
        }
        return (T) views.get(id);
    }

    public <T extends View> T getView(int id, Class<T> clazz) {
        return getView(id);
    }

    public TextView getTv(int id) {
        return getView(id, TextView.class);
    }

    public ImageView getIv(int id) {
        return getView(id, ImageView.class);
    }

    public Button getBt(int id) {
        return getView(id, Button.class);
    }
}
